<?php
namespace Api\Provider\Admin;


use Api\Provider\IndexProvider;
use Api\Service\ImageService;
use Api\Service\ImageSheetService;
use Admin\Enums\SheetStatus;

/**
 * 曲谱图片
 * @author Administrator
 *
 */
class ImageSheetProvider  extends IndexProvider
{
    public function __construct()
    {
        parent::__construct();
    }
    
    /**
     * 曲谱图片保存接口
     * @param unknown $param
     */
    public function save($param){
        //step-1: 保存曲谱
        $Model = M('Sheet');
        $sheet['author_type'] = 10;
        $sheet['creator'] = empty($param['uid']) ? 2 : $param['uid'];
        $sheet['name'] = $param['name'];
        $sheet['s_name'] = $param['s_name'];
        $sheet['desc'] = $param['description'];
        $sheet['singer'] = $param['singer'];
        $sheet['status'] = SheetStatus::$UNCHECKED;
        $sheet_id = $Model->add($sheet);


        //step-2: 保存图片，并且获取图片id
        $imageService = new ImageService();
        $image_sheet = array();
        foreach ($param['pic'] as $key=>$pic) {
            $image['name'] = $pic['name'];
            $image['url'] = $pic['url'];
            $image['creator'] = 2;
            $image_id = $imageService->save($image);
            $image_sheet[$key]['id'] = $image_id;
            $image_sheet[$key]['index'] = $pic['index'];
        }
        
        //step-3: 保存图片和曲谱的关系
        $imageSheetService = new ImageSheetService();
        $imageSheetService->save($image_sheet, $sheet_id);
       
        $this->success($sheet_id);
    }

    /**
     * 同步oss数据到数据库
     * @param $param
     */
    public function syncOssToServer($param)
    {
        //step-1: 保存曲谱
        $Model = M('Sheet');
        //校验曲谱是否存在
        $existSheet = $Model->where(array('name'=>$param['name']))->find();
        if (!empty($existSheet)) {
            $sheet_id = $existSheet['id'];
        } else {
            $sheet['author_type'] = 10;
            $sheet['creator'] = empty($param['uid']) ? 2 : $param['uid'];
            $sheet['name'] = $param['name'];
            $sheet['status'] = SheetStatus::$UNCHECKED;
            $sheet_id = $Model->add($sheet);
        }

        //step-2: 保存图片，并且获取图片id
        $imageService = new ImageService();
        $image_sheet = array();
        foreach ($param['pic'] as $key=>$pic) {
            $image['name'] = $pic['name'];
            $image['url'] = $pic['url'];
            $image['creator'] = 2;
            $image_id = $imageService->save($image);
            $image_sheet[$key]['id'] = $image_id;
            $image_sheet[$key]['index'] = $pic['index'];
        }

        //step-3: 保存图片和曲谱的关系
        $imageSheetService = new ImageSheetService();
        $imageSheetService->save($image_sheet, $sheet_id);

        $this->success($sheet_id);
    }
}

